/*
 * SecurityUrl.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the web-geek, Version 1.0 (the "License");
 *
 */
package org.geek.login.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

@Service
public class SecurityUrl implements FilterInvocationSecurityMetadataSource {
	
	private static final Logger logger = LoggerFactory.getLogger(SecurityUrl.class);

	private AntPathMatcher urlMatcher = new AntPathMatcher();
	private Map<String, Collection<ConfigAttribute>> resourceMap = null;
	
	public void loadResourceDefine() throws Exception {
		this.resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
//		Map<String,Collection<ConfigAttribute>> roles = coreService.getRoleService().getResourceDefine();
//		Iterator<String> it = roles.keySet().iterator();
//		while(it.hasNext()){
//			String key = it.next();
//			Collection<ConfigAttribute> value = roles.get(key);
//		}
//		this.resourceMap.putAll(null);
//		for (Role role : roles) {
//			Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
//			ConfigAttribute ca = new SecurityConfig(role.getRoleName());
//			atts.add(ca);
//			Set<Menu> menus = role.getMenus();
//			// 将资源放到resourceMap中
//			for (Menu menu : menus) {
//				logger.debug("获得角色：[" + role.getRoleName() + "]拥有的功能有："+menu.getMenuTitle() );
//				this.resourceMap.put(menu.getMenuMapping(), atts);
//			}
//		}
		this.resourceMap.put("ss", new ArrayList<ConfigAttribute>());
	}

	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		if (logger.isDebugEnabled()) {
			logger.debug("getAttributes(Object) - start");
		}
		String url = ((FilterInvocation) object).getRequestUrl();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (urlMatcher.match(url, resURL)) {
				Collection<ConfigAttribute> returnCollection = resourceMap.get(resURL);
				if (logger.isDebugEnabled()) {
					logger.debug("getAttributes(Object) - end");
				}
				return returnCollection;
			}
		}
		if (logger.isDebugEnabled()) {
			logger.debug("getAttributes(Object) - end");
		}
		return new ArrayList<ConfigAttribute>();
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}
}
